<template>
  <div>
    <el-dialog v-model="dialog" width="1100" :title="dialogTitle" :before-close="cancelForm">
      <div class="header-container">
        <div class="item-container">
          <p class="item-label">日期:</p>
          <el-date-picker
            v-model="searchParams.datestr"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </div>
        <el-button type="success" @click="getManageListData">
          <el-icon style="margin-right: 10px;">
            <Search />
          </el-icon>
          查询
        </el-button>
      </div>
      <el-table :data="detailData" :border="true" style="width:100%;min-height:100px" v-loading="tableLoading">
        <el-table-column v-for="mapItem in detailDataMap" :prop="mapItem.key" :key="mapItem.key" :label="mapItem.label"
          :min-width="mapItem.width" />
      </el-table>
      <el-table :data="kwData" :border="true" style="width:100%;max-height:380px;overflow-y:auto;margin-top:40px;" v-show="kwData.length">
        <el-table-column v-for="mapItem in kwDataMap" :prop="mapItem.key" :key="mapItem.key" :label="mapItem.label"
          :min-width="mapItem.width" />
      </el-table>
      <el-table :data="lcodeData" :show-header="false" :border="true" style="width:100%;margin-top:40px;" v-show="lcodeDataMap.length">
        <el-table-column v-for="mapItem in lcodeDataMap" :prop="mapItem.key" :key="mapItem.key" :label="mapItem.label"
          :min-width="mapItem.width" />
      </el-table>
    </el-dialog>
  </div>
</template>
  
<script setup lang='ts'>
import { ref, watch, defineProps, reactive } from 'vue';
import { Search } from '@element-plus/icons-vue'

import { reqManagelistDataByAppidAndDateStage, reqManagelistDataByAppidAndDateStageV2 } from '@/api/home/index.ts'
import { divisionHundred, getTodayDateAndTime, transformPercent } from '@/utils/index'
import { PAGE_TYPE_ENUM } from '@/types/home/constData.ts'

interface IDetailData {
  dateRange?: string,
  appid?: string,
  countN?: number,
  countL?: number,
  countImp?: number,
  countPrice?: number | string,
  countClick?: number,
  impRate?: number,
  nrate?: number,
  lcode_list?: any,
  [propName: string]: any
}

interface IKwData {
  kw: string,
  countN: number,
  countNPrice: number,
  countL: number,
  countImp: number,
  countClick: number,
  countPrice: number,
  nrate: number,
  impRate: number,
  clickPrice: number,
  countClickPrice: number,
  clickRate: number,
  [propName: string]: any
}

interface ILcodeData {
  keyName?: string,
  [propName: string]: any
}

interface IDataMap {
  label?: string,
  key?: string,
  width?: number,
  [propName: string]: any
}

interface ISearchParams {
  appid: string,
  btime?: string,
  etime?: string,
  datestr?: any 
}

const dialogTitle = ref<string>('数据详情')
const props = defineProps<{
  appid: string,
  pageType: PAGE_TYPE_ENUM
}>()
const dialog = ref<boolean>(false)

const detailData = ref<IDetailData[]>([])
const tableLoading = ref<boolean>(false)
const detailDataMap = ref<IDataMap>([
  {
    label: '时间范围',
    key: 'dateRange',
    width: 150
  },
  {
    label: 'APPID',
    key: 'appid',
    width: 100
  },
  {
    label: '竞价成功次数',
    key: 'countN',
    width: 80
  },
  {
    label: '竞价失败次数',
    key: 'countL',
    width: 80
  },
  {
    label: '曝光次数',
    key: 'countImp',
    width: 80
  },
  {
    label: '下载次数',
    key: 'countClick',
    width: 80
  },
  {
    label: '花费(元)',
    key: 'countPrice',
    width: 80
  },
  {
    label: '曝光率',
    key: 'impRate',
    width: 80
  },
  {
    label: '竞价胜率',
    key: 'nrate',
    width: 80
  },
])

const lcodeData = ref<ILcodeData[]>([])
const lcodeDataMap = ref<IDataMap>([])

const kwData = ref<IKwData[]>([])
const kwDataMap = ref<IDataMap[]>([
  {
    label: '关键字名称',
    key: 'kw',
    width: 100
  },
  {
    label: '竞价成功次数',
    key: 'countN',
    width: 80
  },
  {
    label: '竞价成功总消耗',
    key: 'countNPrice',
    width: 80
  },
  {
    label: '竞价失败次数',
    key: 'countL',
    width: 80
  },
  {
    label: '曝光次数',
    key: 'countImp',
    width: 70
  },
  {
    label: '点击下载次数',
    key: 'countClick',
    width: 80
  },
  {
    label: '花费(元)',
    key: 'countPrice',
    width: 80
  },
  {
    label: '竞价胜率',
    key: 'nrate',
    width: 80
  },
  {
    label: '曝光率',
    key: 'impRate',
    width: 70
  },
  {
    label: '单次下载费用',
    key: 'clickPrice',
    width: 80
  },
  {
    label: '下载总消耗',
    key: 'countClickPrice',
    width: 80
  },
  {
    label: '下载率',
    key: 'clickRate',
    width: 80
  },
])
// lcode_list 测试用的数据
// const TempLcodeData = [
//   {
//     result: '10001',
//     nums: 12
//   },
//   {
//     result: '10001',
//     nums: 13
//   },
//   {
//     result: '10001',
//     nums: 14
//   },
//   {
//     result: '10001',
//     nums: 15
//   },
//   {
//     result: '10001',
//     nums: 16
//   },
//   {
//     result: '10001',
//     nums: 17
//   },
//   {
//     result: '10001',
//     nums: 17
//   },
//   {
//     result: '10001',
//     nums: 17
//   },
//   {
//     result: '10001',
//     nums: 17
//   },
//   {
//     result: '10001',
//     nums: 17
//   },
//   {
//     result: '10001',
//     nums: 17
//   },
//   {
//     result: '10001',
//     nums: 17
//   },
//   {
//     result: '10001',
//     nums: 17
//   },
//   {
//     result: '10001',
//     nums: 17
//   },
//   {
//     result: '10001',
//     nums: 17
//   },
//   {
//     result: '10001',
//     nums: 17
//   },
//   {
//     result: '10001',
//     nums: 17
//   },
//   {
//     result: '10001',
//     nums: 17
//   },
//   {
//     result: '10001',
//     nums: 18
//   }
// ]

const searchParams = reactive<ISearchParams>({
  appid: '',
  datestr: null
})

const clearLcodeAboutData = () => {
  lcodeData.value = []
  lcodeDataMap.value = []
  kwData.value = []
}

const cancelForm = () => {
  detailData.value = []
  clearLcodeAboutData()
  searchParams.appid = ''
  searchParams.datestr = null
  handleDialog(false)
}
watch(dialog, (newVal) => {
  setTimeout(() => {
    if (!!newVal && props.appid) {
      searchParams.appid = props.appid
      const [ dateO, dateT ] = getTodayDateAndTime()
      searchParams.datestr = [ `${dateO} 00:00:00`,  `${dateO} ${dateT}`]
      getManageListData()
    }
  }, 10);
})

const getManageListData = () => {
  if (!searchParams.datestr) {
    ElMessage({
      type: 'warning',
      message: '请选择时间范围'
    })
    return
  }
  clearLcodeAboutData();
  tableLoading.value = true
  const { appid, datestr } = searchParams;
  const copySearchParams: ISearchParams = {
    appid,
    btime: datestr[0].slice(0, -2) + '00',
    etime: datestr[1].slice(0, -2) + '00'
  }
  let requestFunc = null
  if (props.pageType === PAGE_TYPE_ENUM.TYPE_APP_1) {
    requestFunc = reqManagelistDataByAppidAndDateStage
  } else {
    requestFunc = reqManagelistDataByAppidAndDateStageV2
  }
  requestFunc(copySearchParams).then(res => {
    const { code, data, msg } = res
    tableLoading.value = false
    if (code === 0) {
      const { lcode_list, kw_list, ...rest } = data; 
      const copyData = { ...rest, appid, dateRange: `${copySearchParams.btime?.slice(0, -3)}~${copySearchParams.etime?.slice(0, -3)}` };
      copyData.countPrice = divisionHundred(copyData.countPrice);
      copyData.impRate = transformPercent(copyData.impRate);
      copyData.nrate = transformPercent(copyData.nrate);
      detailData.value = [copyData]
      setLcodeData(lcode_list)
      setKwData(kw_list)
    } else {
      ElMessage({
        type: 'warning',
        message: msg
      })
      detailData.value = []
    }
  })
}

const setLcodeData = (list: any[]) => {
  const tempArrData: any[] = [{}, {}];
  const tempArrDataMap: IDataMap[] = [];
  (list || []).forEach((v: any, i: number) => {
    const { result, nums } = v;
    const tempKey = `data_${i + 1}`;
    tempArrData[0][tempKey] = result
    tempArrData[1][tempKey] = nums
    const tempMap = {
      key: tempKey,
      label: tempKey,
      width: 70
    }
    tempArrDataMap.push(tempMap)
  })
  if (!tempArrDataMap.length) {
    lcodeData.value = []
  } else {
    const tempKey = 'keyName';
    tempArrDataMap.unshift({
      key: tempKey,
      label: tempKey,
      width: 70
    })
    tempArrData[0][tempKey] = '错误码'
    tempArrData[1][tempKey] = '数量'
    lcodeData.value = tempArrData
  }
  lcodeDataMap.value = tempArrDataMap
}

const setKwData = (list: IKwData[]) => {
  const tempArrData: any[] = (list || []).map((v: IKwData) => {
    return {
      ...v,
      countPrice: divisionHundred(v.countPrice),
      impRate: transformPercent(v.impRate),
      nrate: transformPercent(v.nrate),
      clickRate: transformPercent(v.clickRate)
    }
  })
  kwData.value = tempArrData
}

const handleDialog = (val: boolean) => {
  dialog.value = val
}

defineExpose({
  handleDialog
})
</script>
  
<style scope lang="scss">
.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  .item-container {
    display: flex;
    align-items: center;
    margin-right: 20px;
    .item-label {
      min-width: 50px;
    }
  }
}
</style>